package cn.lsoft.undoner.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

/**
 *@fileName   : QrcodeImgCreator.java
 *@description: 二维码图片生成器  用于生产微信二维码图片
 */
public class QrcodeImgCreator {
	
	private final static int width = 256;
	private final static int height = 256;
	private final static String format = "JPG";
	static Logger logger = Logger.getLogger(QrcodeImgCreator.class);
	private static final int BLACK = 0xFF000000;//用于设置图案的颜色
	private static final int WHITE = 0xFFFFFFFF; //用于背景色
	// logo默认边框宽度
    public static final int DEFAULT_BORDER = 2;
    // logo默认边框颜色
    public static final Color DEFAULT_BORDERCOLOR = Color.WHITE;
    //logo地址
    public static final String LOGO_PATH = "E:\\apache-tomcat-7.0.42\\webapps\\images\\";//"F:\\tomcat5.5\\webapps\\tvp_payEntrance_api\\images\\jytlogo.png";//"F:\\tomcat5.5\\webapps\\tvp_payEntrance_api\\images\\jytlogo.png";//
	/*
	 *将传入的文本数据构造成二维码图片，并返回图片名称 
	 *text : 图片内容数据
	 *imgDir : 图片目录
	 * */
	public static String generateImg(String text, String imgDir){
		String qrcodeImgName = "";		//生成的二维码图片名
		if (StringUtil.isEmptyString(text) || StringUtil.isEmptyString(imgDir)){
			return qrcodeImgName;
		}
		try {
			logger.info("开始生成二维码图片, 数据：" + text);
			Hashtable hints = new Hashtable();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//			//hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//			BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
//			
//			qrcodeImgName = RandomStringGenerator.getRandomStringByLength(8) + ".jpg";
//			String qrcodeImgPath = imgDir + qrcodeImgName;
//			logger.info("二维码图片路径：" + qrcodeImgPath);
//			
//		
//			BufferedImage bufferedImage =  toBufferedImage(bitMatrix);
//			createLogoQrcode(bufferedImage, LOGO_PATH, qrcodeImgPath);
			
			BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
			qrcodeImgName = StringUtil.getRandomStringByLength(20) + ".jpg";
			logger.info("二维码图片路径：" + imgDir + qrcodeImgName);
			File outputFile = new File(imgDir + qrcodeImgName);
			MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
			logger.info("生成微信二维码图片成功. 路径" + qrcodeImgName);
			return qrcodeImgName;
			
		} catch (Exception e) {
			e.printStackTrace();
			return qrcodeImgName;
		}
	}
	
	
	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y,  (matrix.get(x, y) ? BLACK : WHITE));
//				image.setRGB(x, y,  (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
			}
		}
		return image;
	}
	
	
	public static void createLogoQrcode(BufferedImage imageBuffer, String logoPath, String qrcodeImagePath){
		 try
	        {
			 	File logoPic = new File(logoPath);
	            if (!logoPic.isFile())
	            {
	                System.out.print("logo file not find !");
	                return ;
	            }
	 
	            /**
	             * 读取二维码图片，并构建绘图对象
	             */
	            if (imageBuffer == null){
	            	System.out.print("imageBuffer is null !");
		            return ;
	            }
	            Graphics2D g = imageBuffer.createGraphics();
	 
	            /**
	             * 读取Logo图片
	             */
	            BufferedImage logo = ImageIO.read(logoPic);
	             
	            int widthLogo = logo.getWidth();
	            int heightLogo = logo.getHeight();
	             
	            // 计算图片放置位置
	            int x = (imageBuffer.getWidth() - widthLogo) / 2;
	            int y = (imageBuffer.getHeight() - logo.getHeight()) / 2;
	 
	            //开始绘制图片
	            g.drawImage(logo, x, y, null);
	            g.drawRoundRect(x, y, widthLogo, heightLogo, 10, 10);
	            g.setColor(DEFAULT_BORDERCOLOR);
	            g.drawRect(x, y, widthLogo, heightLogo);
	           // Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);  
	            g.setStroke(new BasicStroke(DEFAULT_BORDER));
	           // g.draw(shape); 
	            g.dispose();
	             
	            ImageIO.write(imageBuffer, "jpg", new File(qrcodeImagePath));
	        }
	        catch (Exception e)
	        {
	            e.printStackTrace();
	        }
	}
	
	
	public static void main(String[] args){
		QrcodeImgCreator.generateImg("https://123.cn?a_token=xg4a9oom726u02pq", "E:\\");
	}
}
